<?php

namespace App\Http\Controllers;

use App\Models\Appointment;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    // 登陆注册
    function login(Request $req)
    {
        $rule = [
            'username' => 'required|between:2,30',
            'password' => 'required|between:6,30',
        ];
        $data = [
            'username' => $req->username,
            'password' => $req->password
        ];
        $rule = Validator::make($data, $rule);
        if ($rule->fails()) {
            return response()->json(['code' => 201, 'msg' => '账号最短2位,密码最短6位']);
        } else {
            //查询是否有数据
            $select = User::find($req->username);

            if (empty($select)) {
                User::create($data);
                return response()->json(['code' => 200, 'msg' => '创建账号成功']);
            } else {
                if ($select['password'] == $req->password && $select['username'] == $req->username) {
                    return response()->json(['code' => 200, 'msg' => '登陆成功']);
                } else {
                    return response()->json(['code' => 201, 'msg' => '密码错误']);
                }
            }
        }
    }

    // web
    public function update(Request $req)
    {
        $updateUserInfo =  User::where('username', $req->username)->get();
        return response()->json($updateUserInfo);
    }

    public function save(Request $req)
    {
        $updateUserInfo =  User::find($req->username);
        $updateUserInfo->password = $req->password;
        $updateUserInfo->save();
        return response()->json([['code' => 200, 'msg' => '修改信息成功']]);
    }

    public function remove(Request $req)
    {
        Appointment::where('username',$req->username)->delete();
        $remove = User::where('username', $req->username)->delete();
        if ($remove) {
            return response()->json([['code' => 200, 'msg' => '删除成功']]);
        } else {
            return response()->json([['code' => 201, 'msg' => '删除失败']]);
        }
    }

    public function search(Request $req)
    {
        $weddingUserType = User::where('username', 'like', '%' . $req->keyword . '%')->get();
        return response()->json($weddingUserType);
    }
}
